package com.desuntech.business
{
	import C4D.kbmMWConnection;
	import C4D.kbmMWEvent;
	import C4D.kbmMWQuery;
	import C4D.kbmMWResponse;
	
	import com.adobe.crypto.MD5;
	
	import flash.events.Event;
	
	import mx.controls.Alert;

	public class AuthorityBusiness
	{
		private var _conn:kbmMWConnection;
		private var _table:String;
		private var _q:kbmMWQuery;
		private var _loginResultHandler:Function
		private var _username:String;
		private var _autoLogin:Boolean;
		
		public function AuthorityBusiness(conn:kbmMWConnection, table:String)
		{
			_conn = conn;
			_table = table;
		}
		
		public function tryLogin(username:String, pwd:String, autoLogin:Boolean, resultHandler:Function):void {
			_username = username;
			_autoLogin = autoLogin;
			_loginResultHandler = resultHandler;
			_q = new kbmMWQuery();
			_q.Connection = _conn;
			_q.addEventListener(kbmMWEvent.QueryDataAvailableEvent, onDataAvailable);
			_q.addEventListener(kbmMWEvent.FailureEvent, onFault);
			_q.Query = 'SELECT * FROM ' + _table + ' WHERE RYSGZH = \'' + username + '\' AND DLMM = \'' + MD5.hash(pwd) + '\'';
			_q.Open();
		}
		
		private function onDataAvailable(event:Event):void {
			var q:kbmMWQuery = event.target as kbmMWQuery;
			q.removeEventListener(kbmMWEvent.QueryDataAvailableEvent, onDataAvailable);
			q.removeEventListener(kbmMWEvent.FailureEvent, onFault);
			
			var result:Array = (event.target as kbmMWQuery).Rows;
			if(result.length) {
				_loginResultHandler(result[0],true,_autoLogin);
			} else {
				_loginResultHandler(null, false,_autoLogin);
			}
		}
		
		private function onFault(event:Event):void {
			var q:kbmMWQuery = event.target as kbmMWQuery;
			q.removeEventListener(kbmMWEvent.QueryDataAvailableEvent, onDataAvailable);
			q.removeEventListener(kbmMWEvent.FailureEvent, onFault);
			var result:kbmMWResponse;
			result = (event as kbmMWEvent).resultObject as kbmMWResponse;
			Alert.show("Query failure:"+result.header.StatusText+"\n"); 
		}
	}
}